package com.dlc.beijingrfid.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.BindView;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.adapter.OrderDetailAdapter;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.net.bean.OrderDetailBean;
import com.dlc.beijingrfid.sunmi.printerhelper.utils.AidlUtil;
import com.dlc.beijingrfid.sunmi.printerhelper.utils.BluetoothUtil;
import com.dlc.beijingrfid.sunmi.printerhelper.utils.ESCUtil;
import com.dlc.commonlibrary.utils.TimeFormats;
import com.dlc.commonlibrary.widget.TitleBar;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/7/20 0020.
 */

public class OrderDetailActivity extends BaseActivity {

    OrderDetailBean orderDetailBean;
    OrderDetailAdapter mOrderDetailAdapter;
    @BindView(R.id.wash_goods_hint)
    TextView washGoodsHint;
    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.company)
    TextView company;
    @BindView(R.id.send_wash_code)
    TextView sendWashCode;
    @BindView(R.id.nums)
    TextView nums;
    @BindView(R.id.send_wash_time)
    TextView sendWashTime;
    @BindView(R.id.reveice_time)
    TextView reveiceTime;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.print)
    Button print;
    @BindView(R.id.hospital)
    TextView mHospital;
    private boolean isBold, isUnderLine;
    private int record;
    int type;

    private String[] mStrings = new String[] {
        "CP437", "CP850", "CP860", "CP863", "CP865", "CP857", "CP737", "Windows-1252", "CP866",
        "CP852", "CP858", "CP874", "Windows-775", "CP855", "CP862", "CP864", "GB18030", "BIG5",
        "KSC5601", "utf-8"
    };
    Bitmap bitmap;

    @Override
    protected int getLayoutID() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleBar.leftExit(this);

        Bundle bundle = getIntent().getExtras();
        type = bundle.getInt("type");
        orderDetailBean = (OrderDetailBean) bundle.getSerializable("detailData");

        if (orderDetailBean.data.spec_group.size() > 0) {
            InitRecyclerView(orderDetailBean);
            company.setText(orderDetailBean.data.company);
        }
        if (orderDetailBean.data.orderno.contains("W")) {
            washGoodsHint.setText(getString(R.string.send_wash_code));
        } else if (orderDetailBean.data.orderno.contains("D")) {
            washGoodsHint.setText(getString(R.string.send_goods_code));
        } else if (orderDetailBean.data.orderno.contains("T")) {
            washGoodsHint.setText("退貨單號");
        } else {
            washGoodsHint.setText("返洗單號");
        }
        sendWashTime.setText(TimeFormats.formatDateTimeSecend(
            (long) Integer.parseInt(orderDetailBean.data.ctime) * 1000));
        if (TextUtils.isEmpty(orderDetailBean.data.receivetime)
            || orderDetailBean.data.receivetime.equals("0")) {
            reveiceTime.setText(getString(R.string.not_yet_received));
        } else {
            reveiceTime.setText(TimeFormats.formatDateTimeSecend(
                (long) Integer.parseInt(orderDetailBean.data.receivetime) * 1000));
        }
        sendWashCode.setText(orderDetailBean.data.orderno);
        nums.setText(orderDetailBean.data.nums);
        mHospital.setText(orderDetailBean.data.hotel+orderDetailBean.data.office);
         isBold = false;
        isUnderLine = false;
        print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = "";
                printB();
                String orderno = orderDetailBean.data.orderno;
                string = "";

                if (orderno.contains("W")) {
                    string = string + "      " + getString(R.string.washing_oeder) + "\r\n";
                } else if (orderno.contains("D")) {
                    string = string + "      " + getString(R.string.receiving_note) + "\r\n";
                }else if (orderno.contains("B")) {
                    string = string + "      " + "返洗单" + "\r\n";
                }
                string = string + getString(R.string.danhao) + "：" + orderno + "\r\n";
                string = string + "总数量" + "：" + orderDetailBean.data.nums + "\r\n";
                string = string
                        + "医院科室"
                        + "："
                        + orderDetailBean.data.hotel+"_"+orderDetailBean.data.office
                        + "\r\n";
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date curDate = new Date(System.currentTimeMillis());
                String str = formatter.format(curDate);
                string = string + getString(R.string.date) + "：" + str + "\r\n";

//                string = string
//                        + getString(R.string.client)
//                        + "："
//                        + orderDetailBean.data.hotel_number
//                        + "\r\n";

                string = string + "-------------------------";

                for (int i = 0; i < orderDetailBean.data.spec_group.size(); i++) {
                    OrderDetailBean.DataBean.SpecGroupBean bean =
                        orderDetailBean.data.spec_group.get(i);
                    string = string + "\r\n" + (getString(R.string.product_name)
                        + ": "
                        + bean.title
                        + "\r\n"
                        + getString(R.string.classification_specification)
                        + ": "
                        + bean.spec
                        + "\r\n"
                        + "數    量"
                        + ": "
                        + bean.count);
                    string = string + "\r\n";
                    string = string + "-------------------------";
                }
                string = string + "\r\n";
                string = string + getString(R.string.signature) + "：" + "\r\n" + "\r\n";
                string = string + "\r\n" + "\r\n";
                string = string + "-------------------------";
                string = string + "\r\n" + "\r\n";

                //rv = BytesUtil.getBytesFromHexString();
                //AidlUtil.getInstance().sendRawData(BytesUtil.getBytesFromHexString(text));
                //sendData(rv);
                sendData(string, 30);
                //根据当前模式选择进行二维码打印
                int print_size = 8;
                int error_level = 3;
                if (baseApp.isAidl()) {
                    AidlUtil.getInstance().printQr(orderno, print_size, error_level);
                }
            }
        });
    }

    private void printB() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inTargetDensity = 160;
        options.inDensity = 160;
        if (bitmap == null) {
            bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo, options);
        }

        if (baseApp.isAidl()) {
            AidlUtil.getInstance().printBitmap(bitmap, 1);
        } else {
            BluetoothUtil.sendData(ESCUtil.printBitmap(bitmap, 3));
            BluetoothUtil.sendData(ESCUtil.nextLine(3));
        }
    }

    private void sendData(final String content, int size) {
        if (baseApp.isAidl()) {
            AidlUtil.getInstance().printText(content, size, isBold, isUnderLine);
        } else {
            printByBluTooth(content);
        }
    }

    private void printByBluTooth(String content) {
        try {
            if (isBold) {
                BluetoothUtil.sendData(ESCUtil.boldOn());
            } else {
                BluetoothUtil.sendData(ESCUtil.boldOff());
            }

            if (isUnderLine) {
                BluetoothUtil.sendData(ESCUtil.underlineWithOneDotWidthOn());
            } else {
                BluetoothUtil.sendData(ESCUtil.underlineOff());
            }

            if (record < 17) {
                BluetoothUtil.sendData(ESCUtil.singleByte());
                BluetoothUtil.sendData(ESCUtil.setCodeSystemSingle(codeParse(record)));
            } else {
                BluetoothUtil.sendData(ESCUtil.singleByteOff());
                BluetoothUtil.sendData(ESCUtil.setCodeSystem(codeParse(record)));
            }

            BluetoothUtil.sendData(content.getBytes(mStrings[record]));
            BluetoothUtil.sendData(ESCUtil.nextLine(3));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void InitRecyclerView(OrderDetailBean orderDetailBean) {
        mOrderDetailAdapter = new OrderDetailAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mOrderDetailAdapter);
        if (orderDetailBean.data.spec_group != null) {
            mOrderDetailAdapter.addData(orderDetailBean.data.spec_group);
        }
    }

    public static String convertTime(Long time) {
        time = time * 1000;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format.format(new Date(time));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothUtil.disconnectBlueTooth(this);
    }

    private byte codeParse(int value) {
        byte res = 0x00;
        switch (value) {
            case 0:
                res = 0x00;
                break;
            case 1:
            case 2:
            case 3:
            case 4:
                res = (byte) (value + 1);
                break;
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
                res = (byte) (value + 8);
                break;
            case 12:
                res = 21;
                break;
            case 13:
                res = 33;
                break;
            case 14:
                res = 34;
                break;
            case 15:
                res = 36;
                break;
            case 16:
                res = 37;
                break;
            case 17:
            case 18:
            case 19:
                res = (byte) (value - 17);
                break;
            case 20:
                res = (byte) 0xff;
                break;
        }
        return (byte) res;
    }
}
